import router from '@/router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login','/register'] // no redirect whitelist

// 路由权限控制
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken =localStorage.getItem("token")

  if (hasToken) {
      NProgress.done();
      // 用户信息是否拿到
      const userInfo=localStorage.getItem("userInfo")
      if (userInfo) {
        next()
      } else {
        try {
          //没有获取用户信息，发起请求获取用户信息
          this.$http.get('/user/getUserInfo')
          next()
        } catch (error) {
          //若获取用户信息失败，就重新到登录页重新登录
          this.$message.error(err||'Has Error')
          next(`/login?redirect=${to.path}`) //登录完成后重新定向到刚刚离开的页面
          NProgress.done()
        }
      }
  } else {
    //没有拿到token
    if (whiteList.indexOf(to.path) !== -1) { //如果是不需要登录的，就直接放行
      next()
    } else {
      //必须登录的用户给他重定向到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
